﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using System.ComponentModel;

namespace produccion.forms
{
    //Queda pendiente validar movimientos realizados, al eliminar un elemento.

    /// <summary>
    /// Lógica de interacción para FRMequprod.xaml
    /// </summary>
    /// 
    public partial class FRMequprod : Window
    {
        equprod _equprod;

        public FRMequprod()
        {
            InitializeComponent();
            _equprod =(equprod)this.DataContext;
        }

        private void addEqu_Click(object sender, RoutedEventArgs e)
        {
            _equprod.addEquipo();
            datEqu.SelectedIndex = _equprod.lisEquSec.Count - 1;
            if (datEqu.SelectedIndex > 1)
            {
                datEqu.ScrollIntoView(datEqu.Items[datEqu.SelectedIndex - 1]);
                datEqu.ScrollIntoView(datEqu.Items[datEqu.SelectedIndex]);
            }
         
        }

        private void addEmp_Click(object sender, RoutedEventArgs e)
        {
            _equprod.addEmp();
        }

        private void delEmp_Click(object sender, RoutedEventArgs e)
        {
            _equprod.delEmp();
        }

        private void delEqu_Click(object sender, RoutedEventArgs e)
        {
            _equprod.delEqu();

        }

        private void butGua_Click(object sender, RoutedEventArgs e)
        {
            _equprod.guardar(wPnot);
        }

        private void butSal_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void datEqu_LostFocus(object sender, RoutedEventArgs e)
        {
            Boolean errors = (from c in
                                  (from object i in datEqu.ItemsSource select datEqu.ItemContainerGenerator.ContainerFromItem(i))
                              where c != null
                              select Validation.GetHasError(c)).FirstOrDefault(x => x);

            _equprod.ERROR = errors;
        }

        private void datEqu_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.F2) && datEqu.CurrentColumn.DisplayIndex==2)
            {
                FRMbuscar f = new FRMbuscar(new clases.CLSMAEEMPP(), "buscar", "Nombre", "NOMEMP_EMP", "Codigo");
                f.ShowDialog();
               
                if (f.retorno != "" && !_equprod.selEquSec.MAEEQU.CODEMP_EQU.Equals(f.retorno)) {
                    _equprod.selEquSec.CODEMP_EQU = f.retorno;
                   
                }
            }
            if (e.Key.Equals(Key.Enter))
            {
                datEqu_LostFocus(null, null);
            }

        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            
            if (_equprod.CAMBIO)
            {
                if (MessageBox.Show("¿Está seguro que desea salir? se perderan los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        private void datSec_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        private void TxtDatoDigitado_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (TxtDatoDigitado.Text.Trim() == "")
            {
                clases.CLSMAEEQU ClaEmpleadoPorEquipos = new clases.CLSMAEEQU();
                ClaEmpleadoPorEquipos.NOMEMPEQUI = "SinDatos";

                DataSet ds = new DataSet();
                ds.Tables.Add(ClaEmpleadoPorEquipos.listaEquNomEmp());
                DtgEmpleadoPorEquipos.DataContext = ds.Tables[0];
            }
            else
            {
                clases.CLSMAEEQU ClaEmpleadoPorEquipos = new clases.CLSMAEEQU();
                ClaEmpleadoPorEquipos.NOMEMPEQUI = TxtDatoDigitado.Text.Trim();

                DataSet ds = new DataSet();
                ds.Tables.Add(ClaEmpleadoPorEquipos.listaEquNomEmp());
                DtgEmpleadoPorEquipos.DataContext = ds.Tables[0];

            }
        }
        
            //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        } 

    }

    public class equprod:ObservableObject 
    {
        public equprod()
        {
            MDOgeneral.conectar();
            strTituloVentana = "Equipos de producción - Usuario: " + MDOgeneral.usuario + " - [FRMeqprod]";
        }

        private string _strTituloVentana;
        public string strTituloVentana
        {
            get { return _strTituloVentana; }
            set { _strTituloVentana = value; RaisePropertyChangedEvent("strTituloVentana"); }
        }

        private List<clases.CLSMAESEC> _lisSec=new clases.CLSMAESEC().listarSecciones();
        public List<clases.CLSMAESEC> lisSec {
            get { return _lisSec; }
            set { _lisSec = value;
            RaisePropertyChangedEvent("lisSec");
            }
        }

        private clases.CLSMAESEC _selSec = new clases.CLSMAESEC() ;
        public clases.CLSMAESEC selSec
        {
            get { return _selSec; }
            set
            {
                if (CAMBIO) {
                    if (MessageBox.Show("¿Está seguro que desea cambiar de elemento? se perderán los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
                _selSec = value;
                clsEquSec EquSec = new clsEquSec();
                EquSec.MAEEQU.CODSEC_EQU = _selSec.CODSEC_SEC;
                lisEquSec = EquSec.listaEquSec();
                CAMBIO = false;
                RaisePropertyChangedEvent("selSec");
            }
        }

        private ObservableCollection<clsEquSec> _lisEquSec=new ObservableCollection<clsEquSec>();
        public ObservableCollection<clsEquSec> lisEquSec {
            get { return _lisEquSec; }
            set { _lisEquSec = value;
            RaisePropertyChangedEvent("lisEquSec");
            }
        }

        private clsEquSec _selEquSec = new clsEquSec();
        public clsEquSec selEquSec
        {
            get { return _selEquSec; }
            set
            {
                _selEquSec = value;
                RaisePropertyChangedEvent("selEquSec");
            }
        }

        public void addEquipo() 
        {
            clsEquSec EquSec = new clsEquSec();
            EquSec.MAEEQU.CODSEC_EQU = selSec.CODSEC_SEC;
            EquSec.MAEEQU.CODEQU_EQU = "";
            EquSec.MAEEQU.CODEMP_EQU = "";
            EquSec.MAEEQU.PORCEN_EQU = 0;
            EquSec.NUEVO = true;
            CAMBIO = true;
            lisEquSec.Add(EquSec);
            lisEquSec.GroupBy(x => x.MAEEQU.CODEQU_EQU);
        }

        public void addEmp() {
            if (selEquSec != null)
            {
                clsEquSec EquSec = new clsEquSec();
                EquSec.MAEEQU.CODSEC_EQU = selSec.CODSEC_SEC;
                EquSec.MAEEQU.CODEQU_EQU = selEquSec.MAEEQU.CODEQU_EQU;
                EquSec.MAEEQU.CODEMP_EQU = "";
                EquSec.MAEEQU.PORCEN_EQU = 0;
                EquSec.NUEVO = true;
                CAMBIO = true;
                lisEquSec.Add(EquSec);
                lisEquSec.GroupBy(x => x.MAEEQU.CODEQU_EQU);
            }
        }

        public void delEmp() {

            if (selEquSec != null)
            {
                if (selEquSec.BORRAR)
                {
                    selEquSec.BORRAR = false;
                }
                else
                {
                    selEquSec.BORRAR = true;
                    if (selEquSec.NUEVO == true)
                    {
                        lisEquSec.Remove(selEquSec);
                    }
                }
            }

            CAMBIO = true;
        }

        public void delEqu(){

            if (selEquSec != null)
            {
                Boolean borrar = !selEquSec.BORRAR;
                string equ = selEquSec.MAEEQU.CODEQU_EQU;
                for (int i = 0; i <= lisEquSec.Count - 1; i++)
                {
                    if (lisEquSec[i].MAEEQU.CODEQU_EQU.Equals(equ))
                    {

                        lisEquSec[i].BORRAR = borrar;
                        if (lisEquSec[i].NUEVO == true && borrar)
                        {
                            lisEquSec.RemoveAt(i);
                            i = i - 1;
                        }
                    }
                }
            }

            CAMBIO = true;
        }

        public void guardar(WrapPanel wPnot) {

            if (MessageBox.Show("¿Está seguro que desea guardar los cambios realizados?", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
            {
                return;
            }

            try
            {
      

            List<clases.CLSMAEEQU> lisEquAdd = new List<clases.CLSMAEEQU>();
            List<clases.CLSMAEEQU> lisEquDel = new List<clases.CLSMAEEQU>();

            for (int i = 0; i <= lisEquSec.Count - 1; i++)
            {
                    if (lisEquSec[i].NUEVO == true)
                    {
                        lisEquAdd.Add(lisEquSec[i].MAEEQU);
                    }
                    if (lisEquSec[i].BORRAR == true)
                    {
                        lisEquDel.Add(lisEquSec[i].MAEEQU);
                    }
            }

       
                if (new clases.CLSMAEEQU().guardar(lisEquAdd, lisEquDel) > 0)
                {

                    new MDOgeneral.notificar(wPnot, "Los cambios fueros guardados correctamente.", true);
                    clsEquSec EquSec = new clsEquSec();
                    EquSec.MAEEQU.CODSEC_EQU = _selSec.CODSEC_SEC;
                    lisEquSec = EquSec.listaEquSec();
                    CAMBIO = false;
                
                }
                else {
                    new MDOgeneral.notificar(wPnot, "Los cambios no pueden ser guardados.", false);
                }
            
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        
        }

        public class clsEquSec : ObservableObject
        {

            public ObservableCollection<clsEquSec> listaEquSec() {
              
                ObservableCollection<clsEquSec> lisEquSec = new ObservableCollection<clsEquSec>();
                try
                {
                    
                    DataTable val = MAEEQU.listaEquSec();
                    foreach (DataRow r in val.Rows)
                    {

                        clsEquSec EquSec = new clsEquSec();
                        EquSec.MAEEQU.CODEMP_EQU = r["CODEMP_EQU"].ToString();
                        EquSec.MAEEQU.CODEQU_EQU = r["CODEQU_EQU"].ToString();
                        EquSec.MAEEQU.CODSEC_EQU = r["CODSEC_EQU"].ToString();
                        EquSec.MAEEQU.PORCEN_EQU = Double.Parse(r["PORCEN_EQU"].ToString());
                        EquSec.MAEEQU.EXISTE = true;
                        EquSec.MAEEQU.CAMBIO = false;
                        EquSec.NOMEMP = r["NOMEMP"].ToString();
                        lisEquSec.Add(EquSec);
                    }
                 
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                return lisEquSec;
            }
           
            #region  Propiedades

            private clases.CLSMAEEQU _MAEEQU = new clases.CLSMAEEQU();
            public clases.CLSMAEEQU MAEEQU
            {
                get { return _MAEEQU; }
                set
                {
                    _MAEEQU = value;
                    RaisePropertyChangedEvent("MAEEQU");
                }
            }

            public string CODEMP_EQU
            {
                get { return MAEEQU.CODEMP_EQU; }
                set {

                    if (MAEEQU.CODEMP_EQU != value)
                    {
                        MAEEQU.CODEMP_EQU = value;

                        clases.CLSMAEEMPP MAEEMPP = new clases.CLSMAEEMPP { CODEMP_EMP = MAEEQU.CODEMP_EQU };
                        MAEEMPP.consultar();
                        NOMEMP = MAEEMPP.NOMEMP_EMP;
                        if (!MAEEMPP.EXISTE && MAEEQU.CODEMP_EQU.Length >= 5)
                        {
                            FRMbuscar f = new FRMbuscar(new clases.CLSMAEEMPP(), "buscar", "Nombre", "NOMEMP_EMP", "Codigo", CODEMP_EQU);
                            f.ShowDialog();
                            if (f.retorno != "" && !MAEEQU.CODEMP_EQU.Equals(f.retorno))
                            {
                                CODEMP_EQU = f.retorno;
                            }
                        }

                        RaisePropertyChangedEvent("CODEMP_EQU");
                    }
                }
            
            
            }

            public Double PORCEN_EQU
            {
                get { return MAEEQU.PORCEN_EQU; }
                set
                {
                    MAEEQU.PORCEN_EQU = value;
                    RaisePropertyChangedEvent("PORCEN_EQU");
                }
            }

            private string _NOMEMP;
            public string NOMEMP
            {
                get { return _NOMEMP; }
                set
                {
                    _NOMEMP = value;
                    RaisePropertyChangedEvent("NOMEMP");
                }
            }


            private Boolean _BORRAR;
            public Boolean BORRAR
            {
                get { return _BORRAR; }
                set
                {
                    _BORRAR = value;
                    RaisePropertyChangedEvent("BORRAR");
                }
            }

            private Boolean _NUEVO=false;
            public Boolean NUEVO
            {
                get { return _NUEVO; }
                set
                {
                    _NUEVO = value;
                    RaisePropertyChangedEvent("NUEVO");
                }
            }

            #endregion
        }

        private Boolean _CAMBIO = false;
        public Boolean CAMBIO 
        {
            get {

                return _CAMBIO;
            }
            set {
                _CAMBIO = value;
                RaisePropertyChangedEvent("CAMBIO");
            }        
        }
       
        private Boolean _ERROR = false;
        public Boolean ERROR
        {
            get
            {

                return _ERROR;
            }
            set
            {
                _ERROR = value;
                RaisePropertyChangedEvent("ERROR");
            }
        }    
    
    }

}

namespace ReglasValidacion
{
    //validar equipo produccion
    public class esOKequprod : ValidationRule
    {
        public produccion.forms.equprod equprod { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult res;

            if (String.IsNullOrEmpty(equprod.selEquSec.MAEEQU.CODEQU_EQU))
            {
                if (!String.IsNullOrEmpty(equprod.selEquSec.MAEEQU.CODEMP_EQU))
                {
                    return new ValidationResult(false, "El codigo del equipo no puede estar vacio.");
                }
                return new ValidationResult(true, null);
            }
            if (!equprod.selEquSec.MAEEQU.EXISTE)
            {
                res = new esOKcadena { Maxc = 5, Minc = 1 }.Validate(equprod.selEquSec.MAEEQU.CODEQU_EQU, cultureInfo);
                if (!res.IsValid)
                {
                    return new ValidationResult(false, res.ErrorContent.ToString().Replace("campo", "codigo del equipo"));
                }

                res = new esOKcadena { Maxc =5, Minc = 1 }.Validate(equprod.selEquSec.MAEEQU.CODEMP_EQU, cultureInfo);
                if (!res.IsValid)
                {
                    return new ValidationResult(false, res.ErrorContent.ToString().Replace("campo", "codigo del empleado"));
                }


                if (equprod.selEquSec.MAEEQU.existe())
                {
                    return new ValidationResult(false, "El empleado ingresado ya existe en el equipo.");
                }
                else
                {
                    if (equprod.lisEquSec.ToList().FindAll(r => r.MAEEQU.CODEQU_EQU.Equals(equprod.selEquSec.MAEEQU.CODEQU_EQU) & r.MAEEQU.CODEMP_EQU.Equals(equprod.selEquSec.MAEEQU.CODEMP_EQU) & r.MAEEQU.CODSEC_EQU.Equals(equprod.selEquSec.MAEEQU.CODSEC_EQU)).Count > 1)
                    {
                        return new ValidationResult(false, "El empleado ingresado ya existe en el equipo.");
                    }
                }
                if (!new produccion.clases.CLSMAEEMPP { CODEMP_EMP = equprod.selEquSec.MAEEQU.CODEMP_EQU }.existe()) {
                    return new ValidationResult(false, "El empleado ingresado no existe.");
                }

            }
            
            return new ValidationResult(true, null);
        }
    }

}
